<template>
  <div class="flex direction-column height-100">
    <el-form inline>
      <el-form-item label="周期">
        <el-date-picker
          style="width: 360px;"
          type="daterange" v-model="range" :clearable="false"
          format="yyyy-MM-dd" value-format="yyyy-MM-dd"
          range-separator="至"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="clickSearch">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="chart-content">
      <v-chart :option="chartOption" style="width:100%;height:100%;"></v-chart>
    </div>
  </div>
</template>

<script>
import { select15MinutesTagValueList } from '@/api/indicator'

export default {
  name: 'chart-modal',
  props: ['start', 'end', 'modalUnit', 'modalTitle', 'indicatorCode'],
  data () {
    let { start, end } = this
    let xaxisData = []
    if (!start || !end) {
      end = this.$dayjs().format('YYYY-MM-DD')
      start = this.$dayjs().subtract(1, 'year').format('YYYY-MM-DD')

      const ret = []
      let temp = end
      while (temp !== start) {
        ret.unshift(temp)
        temp = this.$dayjs(temp).subtract(1, 'day').format('YYYY-MM-DD')
      }
      ret.unshift(start)
      xaxisData = [...ret]
    }
    return {
      range: [start, end],
      lists: [],
      xaxisData,
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    },
    chartOption () {
      const { xaxisData, themeColor, modalUnit } = this
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
        },
        grid: {
          left: '6%',
          right: '6%',
          top: '10%',
          bottom: '10%'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xaxisData
        },
        yAxis: {
          type: 'value',
          name: modalUnit,
          axisLine: {
            show: true
          },
        },
        series: [
          {
            name: '分析数据',
            type: 'line',
            smooth: true,
            itemStyle: {
              color: themeColor
            },
            data: this.lists
          }
        ],
      }
    },
  },
  mounted () {
    this.query()
  },
  methods: {
    query () {
      const [startDatatTime, endDatatTime] = this.range
      const indicatorCode = this.indicatorCode
      return select15MinutesTagValueList({
        indicatorCode,
        startDatatTime,
        endDatatTime
      }).then(res => {
        if (res.code === 200) {
          this.xaxisData = res.data.map(v => this.$dayjs(v.dataTime).format('YYYY-MM-DD'))
          this.lists = res.data.map(v => Number(v.val))
        }
      })
    },
    clickSearch () {
      this.query()
    }
  },
}
</script>

<style scoped>
.chart-content {
  flex: 1;
}
</style>
